package com.shenhua.test.config;


import com.shenhua.kunpeng.dto.FillUserDTO;
import com.shenhua.kunpeng.utils.FillUserDTOContextHolder;
import com.shenhua.kunpeng.utils.TenantIdContextHolder;
import com.shenhua.test.constants.WsContants;
import com.shenhua.test.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.MapUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

@Aspect
@Component
@Slf4j
@Order(0)
public class UserAspect {

    @Pointcut("execution(public * com.shenhua.test.controller..*.*(..))")
    public void controller() {
    }

    @Before("controller()")
    public void deBefore() throws UnsupportedEncodingException {
        Map<String, String> headers = RequestUtils.getHeaders();
        if (MapUtils.isEmpty(headers)) {
            return;
        }
        String tenantId = headers.getOrDefault(WsContants.TENANT_ID, "");
        String tenantUserId = headers.getOrDefault(WsContants.TENANT_USER_ID, "");
        String tenantOperateName = headers.getOrDefault(WsContants.TENANT_OPERATE_NAME, "");

        FillUserDTO fillUserDTO = new FillUserDTO();

        FillUserDTOContextHolder.set(fillUserDTO);
        if (StringUtils.isNotBlank(tenantOperateName)) {
            String decode = URLDecoder.decode(tenantOperateName, "utf-8");
            fillUserDTO.setUserName(decode);
            fillUserDTO.setRealName(decode);
        }
        if (StringUtils.isNotBlank(tenantUserId)) {
            fillUserDTO.setUserId(Long.parseLong(tenantUserId));
        }
        if (StringUtils.isNotBlank(tenantId)) {
            TenantIdContextHolder.set(Long.parseLong(tenantId));
        }
    }

    @AfterReturning(returning = "ret", pointcut = "controller()")
    public void doAfterReturning(Object ret) {
        FillUserDTOContextHolder.remove();
        TenantIdContextHolder.remove();
    }
}
